package com.itasura.unitofwork;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sailor wang
 * @date 2018/10/15 下午2:41
 * @description
 */
@Slf4j
public class StudentRepository implements IUnitOfWork<Student> {

    private Map<String, List<Student>> context;

    private StudentDatabase studentDatabase;

    public StudentRepository(Map<String, List<Student>> context, StudentDatabase studentDatabase) {
        this.context = context;
        this.studentDatabase = studentDatabase;
    }

    @Override
    public void registerNew(Student entity) {
        register(entity,INSERT);
    }

    @Override
    public void registerModify(Student entity) {
        register(entity,MODIFY);
    }

    @Override
    public void registerDelete(Student entity) {
        register(entity,DELETE);
    }

    @Override
    public void commit() {
        if (context == null || context.size() == 0){
            return;
        }
        if (context.containsKey(INSERT)){
            commitInsert();
        }

        if (context.containsKey(MODIFY)){
            commitModify();
        }

        if (context.containsKey(DELETE)){
            commitDelete();
        }
        log.info("commit finished");
    }

    private void register(Student student, String operation){
        List<Student> students = context.get(operation);
        if (students == null){
            students = Lists.newArrayList();
        }
        students.add(student);
        context.put(operation,students);
    }

    private void commitInsert(){
        context.get(INSERT).forEach(student -> {
            studentDatabase.insert(student);
        });
    }

    private void commitModify(){
        context.get(MODIFY).forEach(student -> {
            studentDatabase.modify(student);
        });
    }

    private void commitDelete(){
        context.get(DELETE).forEach(student -> {
            studentDatabase.delete(student);
        });
    }
}